<template>
	<div class="recharge-bank px-[35px] pt-4">
		<wallet-select-bank
			v-if="rechargeName && bankList.length >= 1"
			v-model:modelValue="bankValue"
			:title="$t('wallet.bankSelect')"
			:options="bankList"
			modifyClass="bg-bg-3 pl-[12px]"
			:ableDeleted="false" />
		<recharge-header :icon="paymentMethodCode" :name="rechargeName" v-else />
		<div class="py-[18px]">
			<div class="mb-[10px] text-t-1">{{ $t('recharge.amount') }}</div>
			<wallet-input-amount
				v-model="amount"
				:placeholder="$t('recharge.amountPlaceholder')"
				hideMax />
			<div class="mt-2 mb-2 flex flex-wrap gap-[6px]">
				<div
					v-for="item in quickList"
					:key="item"
					class="bg-bg-3 rounded-[20px] px-[10px] py-2"
					@click="amount = String(item)">
					<up-amount :value="item" />
				</div>
			</div>
			<div v-if="!limitError" class="limit-range flex-wrap text-sm mt-2 text-t-3">
				<div class="flex-cross-center" style="margin-right: 8px">
					{{ $t('recharge.min') }}&nbsp;
					<up-amount :value="min" />
				</div>
				<div class="flex-cross-center">
					{{ $t('recharge.max') }}&nbsp;
					<up-amount :value="max" />
				</div>
			</div>
			<div v-else class="text-sm text-danger flex-cross-center">
				<base-icon name="mistake" size="15" style="margin-right: 4px" />
				{{ $t('recharge.limitError') }}
				(
				<up-amount :value="min" />
				~
				<up-amount :value="max" />
				)
			</div>
			<base-button
				type="primary"
				block
				round
				:disabled="submitDisabled"
				:loading="loading"
				@click="beforeSubmit"
				style="margin-top: 20px">
				{{ $t('wallet.deposit') }}
			</base-button>
			<div class="mt-[18px]">
				<wallet-course :tell-msg="tellMsg" :wallet-type="0" currency-type="flat" />
			</div>

			<div class="mt-[18px]">
				<wallet-tip-desc :type-code="paymentMethodCode" />
			</div>
		</div>
		<form ref="formRef" method="POST" target="_blank">
			<input
				type="text"
				v-for="(value, name) in formInfo"
				hidden
				:name="name"
				:value="value"
				:key="name" />
		</form>
		<validate-realname v-model="show" @submit="onSubmit" />
	</div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref } from 'vue'
import WalletTipDesc from '../components/wallet-tip-desc.vue'
import { showError } from '@/utils'
import { deposit, getDepositFlatInfo } from '@/api/wallet'
import { UpAmount } from '@/components/up'
import { BaseButton } from '@/components/base'
import ValidateRealname from '@/views/wallet/validate/validate-realname.vue'
import WalletCourse from '../components/wallet-course.vue'
import { useAppStore, useWalletStore } from '@/store'
import { BaseIcon } from '@/components/base'
import WalletInputAmount from '@/views/wallet/components/wallet-input-amount.vue'
import WalletSelectBank from '@/views/wallet/components/wallet-select-bank.vue'
import RechargeHeader from '@/views/wallet/components/recharge-header.vue'

const walletStore = useWalletStore()
const data = computed(() => walletStore.depositData)

const paymentMethodCode = computed(() => data.value.currentType)
const merchantCode = computed(() => data.value.merchantCode)
const bankCode = ref(data.value.bankCode)
const channelId = ref('')
const min = ref('')
const max = ref('')
const quickList = ref([])
const tellMsg = ref('')

const bankValue = ref(walletStore.depositData.selectedBank?.id || 0)
const rechargeName = ref(walletStore.depositData.merchantCode)

const bankList: any = computed({
	get: () => {
		return walletStore.depositBankPaymentList.map((item: any, index: any) => ({
			id: index,
			text: item.name,
			code: item.code,
			img: item.icon,
			type: 'server'
		}))
	},
	set: (newValue) => (bankList.value = newValue)
})

const getRechargeBankInfo = async () => {
	try {
		const { data } = await getDepositFlatInfo({
			paymentMethodCode: paymentMethodCode.value,
			merchantCode: merchantCode.value
		})
		channelId.value = data.channelId
		min.value = data.depositMin
		max.value = data.depositMax
		quickList.value = data.quickAmount
		tellMsg.value = data.tellMsg
		needRealName.value = data.needRealName
	} catch (e) {
		console.log(e)
	}
}

const show = ref(false)
const needRealName = ref(false)
const beforeSubmit = () => {
	if (!needRealName.value) {
		onSubmit('')
	} else {
		show.value = true
	}
}

onMounted(() => {
	getRechargeBankInfo()
})

const appStore = useAppStore()
const uuid = computed(() => appStore.uuid)
const amount = ref('')
const submitDisabled = computed(() => !amount.value || limitError.value)

const limitError = computed(
	() =>
		amount.value &&
		(Number(amount.value) < Number(min.value) || Number(amount.value) > Number(max.value))
)
const loading = ref(false)

const formRef: any = ref(null)
const formInfo = ref({
	amount: 0,
	backend_url: '',
	currency: '',
	member_id: '',
	partner_code: '',
	partner_orderid: '',
	redirect_url: '',
	remark: '',
	service_version: '',
	sign: '',
	trans_time: ''
})
const otherChannel = ['eesiepay', 'help2pay']
let page: any = null
const onSubmit = async (realName: any) => {
	try {
		loading.value = true
		if (!otherChannel.includes(merchantCode.value)) {
			page = window.open('', '_blank')
		}
		const codeValue = bankValue.value
			? bankList.value[Number(bankValue.value)].code
			: bankCode.value

		const params = {
			channelId: channelId.value,
			code: codeValue,
			amount: amount.value,
			orderId: uuid.value,
			realName: realName
		}
		const res = await deposit(params)
		// router.back()
		walletStore.setWalletDepositNextPopupShow(false)
		if (otherChannel.includes(merchantCode.value)) {
			formRef.value.action = res.data.showurl
			formInfo.value = res.data.body
			await nextTick(() => {
				formRef.value.submit()
			})
		} else if (res.data.channel === 'help2pay') {
			console.log('console')
		} else {
			page && (page.location = res.data.showurl)
		}
		loading.value = false
	} catch (error: any) {
		loading.value = false
		page && page.close()
		showError(error)
	}
}
</script>
<style lang="scss" scoped></style>
